<?php
namespace app\api\controller;
use think\Controller;
use app\api\validate\User as valuser;
use app\common\exception\BaseException;
use app\api\model\User as UserModel;
class User extends Controller
{
    public function register()
    {
        $data = $this->request->param();
        $validate = new valuser;

        // 格式检查
        if (!$validate->check($data)) {
            throw new BaseException($validate->getError());
        } else {
            // 检测用户是否重复
            $user = new UserModel();
            $check = $user::where('username', $this->request->param('username'))->find();
            if($check) {
                throw new BaseException('用户已存在，不能重复创建', 423);
            }else {
                $newUser = [
                    'username'=>  $this->request->param('username'),
                    'password'=>  md5(md5($this->request->param('password')).'ye'),
                    'email'=> $this->request->param('email'),
                    'create_time'=> time(),
                    'accesstoken'=> md5(md5($this->request->param('username')).'ye')
                ];
                $result = $user->save($newUser);
                if($result) {
                    $success = [
                        'msg'=> '用户创建成功',
                        'code'=> 20000
                    ];
                    return json($success, 200);
                }
            }
        }  
    }

    public function login() {
        $user = new UserModel();
        $data = $user::where('username', $this->request->param('username'))->where('password', $this->request->param('password'))->field(['username,accesstoken,email'])->find();
        if($data) {
            $success = [
                'msg'=> '用户登录成功',
                'code'=> 20000,
                'data'=> $data
            ];
            return json($success, 200);
        }else {
            throw new BaseException('用户密码错误，请重新输入', 424);
        }
    }

    

}
